package cn.xiaolang.function.design_pattern.duty_chain_pattern;

import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

import java.util.LinkedList;
import java.util.List;

/**
 * 实现过滤器链
 * @see Filter
 * @author Dean
 * @date 2020-12-23
 */
@Slf4j
public class MyFilterChain implements FilterChain {

    @Setter
    private List<Filter> filters = new LinkedList<>();

    private int position = 0;

    /**
     * 执行所有的过滤器
     */
    @Override
    public void doFilter() {
        // 必须有终止条件
        if (position == filters.size()) {
            log.info("doFilter over!");
            // reset
            this.position = 0;
            return;
        }
        // 执行下一个过滤器
        this.position++;
        log.info("doFilter[index={}]", position);
        Filter nextFilter = filters.get(position - 1);
        nextFilter.doFilter(this);
    }
}
